<template>
  <div class="wrapper">
    <h2 class="title">保存文件</h2>
    <div class="add">
      <span>文件名:</span>
      <el-input class="input-name" v-model="fileName" placeholder="请输入文件名"></el-input>
      <span>文件地址:</span>
      <el-input class="input-url" v-model="fileUrl" placeholder="请输入文件地址"></el-input>
      <el-button class="btn-save" type="primary" @click="handleAdd">添加</el-button>
    </div>
    <div class="table-area">
      <el-table ref="userTable" style="width: 100%" height="100%" :data="dataList" align="center" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="索引" align="center" width="55">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="文件名" align="center">
          <template slot-scope="scope">{{ scope.row.fileName }}</template>
        </el-table-column>
        <el-table-column label="文件地址" align="center">
          <template slot-scope="scope">{{ scope.row.fileUrl }}</template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="240"
        >
          <template slot-scope="scope">
            <div class="btn-box">
              <el-button class="btn-down" size="medium" circle type="primary" v-if="scope.row.flag == 0" @click="handleDown(scope.row)"><i class="el-icon-download"></i></el-button>
              <el-button class="btn-down" size="medium" circle type="primary" v-if="scope.row.flag == 1"><i class="el-icon-loading
  "></i></el-button>
              <el-button class="btn-down" size="medium" circle type="success" v-if="scope.row.flag == 2" :disabled="true"><i class="el-icon-check"></i></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="table-footer">
      <div class="btn-delete" @click="handleMutilDel">批量删除</div>
      <div class="btn-delete done" @click="handleDelDone">删除已下载</div>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
export default {
  name: 'Download',
  data () {
    return {
      fileUrl: '',
      fileName: '',
      dataList: [],
      deleteIndexs: []
    }
  },
  methods: {
    getRecords () {
      let list = window.localStorage.getItem('history')
      if (list && list.length) {
        this.dataList = JSON.parse(list)
      }
    },
    setRecords (list) {
      let records = list || this.dataList
      window.localStorage.setItem('history', JSON.stringify(records))
    },
    handleSelectionChange (val) {
      let list = []
      val.map(item => {
        list.push(item.id)
      })
      this.deleteIndexs = list
    },
    handleAdd () {
      if (this.fileName == '') {
        this.$message({ type: 'warning', message: '请输入文件名!' })
        return
      }
      if (this.fileUrl == '') {
        this.$message({ type: 'warning', message: '请输入文件地址!' })
        return
      }
      let index = this.dataList.length
      let regExp = /\"|\'|\‘|\’|\“|\”/gi // 过滤引号
      let fileName = this.fileName.replace(regExp, '')
      let fileUrl = this.fileUrl.replace(regExp, '')
      this.dataList.unshift({
        id: index,
        fileName,
        fileUrl,
        flag: 0
      })
      this.setRecords()
      setTimeout(() => {
        this.fileName = ''
        this.fileUrl = ''
      }, 100)
    },
    handleMutilDel () {
      let newList = this.dataList.filter(item => !this.deleteIndexs.includes(item.id))
      this.deleteIndexs = []
      this.dataList = newList
      this.setRecords(newList)
    },
    handleDelDone () {
      let newList = this.dataList.filter(item => item.flag != 2)
      this.dataList = newList
      this.setRecords(newList)
    },
    handleDown (row) {
      row.flag = 1
      this.urlToBlob(row.fileUrl).then(res => {
        FileSaver.saveAs(res, row.fileName)
        row.flag = 2
        this.setRecords()
      }).catch((e) => {
        console.log('e', e)
        row.flag = 0
      })
    },
    urlToBlob (url) {
      return new Promise(resolve => {
        let xhr = new XMLHttpRequest()
        xhr.open('get', url, true)
        xhr.onload = function () {
          if (this.status === 200) {
            resolve(this.response)
          }
        }
        xhr.responseType = 'blob'
        xhr.send()
      })
    }
  },
  created () {
    this.getRecords()
  }
}
</script>

<style scoped lang="scss">
.wrapper {
  position: absolute;
  top: 0;
  right: 30px;
  bottom: 0;
  left: 30px;
  margin: 0;
  display: flex;
  flex-direction: column;
  border: 1px solid #f5f5f5;
  margin: 0 auto;
  .title {
    text-align: center;
  }
  .add {
    margin-bottom: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    .input-name {
      width: 260px;
    }
    .input-url {
      width: 300px;
    }
    .btn-save {
      margin-left: 15px;
    }
    > span {
      width: 100px;
      text-align: right;
      margin-right: 8px;
    }
  }
  .table-area {
    flex: 1;
    min-height: 0;
  }
  .table-footer {
    display: flex;
    .btn-delete {
      font-size: 14px;
      margin: 0 15px;
      line-height: 40px;
      color: #ff3300;
      cursor: pointer;
      &.done {
        color: #38a28a;
      }
    }
  }
}

</style>
